<template>
  <div class="mod-user">
    <avue-crud
      ref="crud"
      :page="page"
      :data="dataList"
      :option="tableOption"
      @search-change="searchChange"
      @refresh-change="refreshChange"
      @selection-change="selectionChange"
      @on-load="getDataList"
      @search-reset="searchReset"
    >
      <!--@sort-change="changeTableSort"-->
      <template slot="menuLeft">
        <el-button
          v-if="isAuth('user:userLevel:updateGrowth')"
          type="primary"
          size="small"
          @click="updateGrowth()"
          :disabled="dataListSelections.length <= 0"
        >{{$t('user.updateGrowth')}}</el-button>
        <el-button
          type="primary"
          size="small"
          @click="updateTags()"
          :disabled="dataListSelections.length <= 0"
        >{{$t('user.tagging')}}</el-button>
        <el-button
          v-if="isAuth('user:userLevel:updateScore')"
          type="primary"
          size="small"
          @click="updateScore()"
          :disabled="dataListSelections.length <= 0"
        >{{$t('user.updateScore')}}</el-button>
        <el-button
          v-if="isAuth('platform:coupon:sendUserCoupon')"
          type="primary"
          size="small"
          @click="updateCoupon()"
          :disabled="dataListSelections.length <= 0"
        >{{$t('user.sendCoupons')}}</el-button>
        <el-button
          v-if="isAuth('platform:user:updateBalance')"
          type="primary"
          size="small"
          @click="updateBalance(null,1)"
          :disabled="dataListSelections.length <= 0"
        >{{$t('user.modifyBalance')}}</el-button>
        <el-button
          v-if="isAuth('platform:user:import')"
          type="primary"
          size="small"
          @click="importUser()"
          :disabled="importDisabled"
        >{{$t('user.userImport')}}</el-button>
        <el-button
          type="primary"
          size="small"
          @click="exportUser()"
          :disabled="exportDisabled"
        >{{$t('user.export')}}</el-button>
      </template>
      <template slot-scope="scope" slot="pic">
        <img src="~@/assets/img/userImg.jpg" v-if="!scope.row.pic" width="130px" />
        <img :src="scope.row.pic" v-else />
      </template>
      <template slot-scope="scope" slot="search">
        <el-form
          ref="form"
          :model="searchForm"
          style="width: 830px;margin-left: 20px; display: inline-block;"
          label-width="100px"
        >
          <el-row>
            <el-form-item :label="$t('user.customerLabel')" prop="dynamicTags" label-width="120">
              <!-- <el-button style="width: 50px;margin-left: 20px"></el-button> -->
              <el-button @click="clearAllTags" size="small">{{$t('seckill.unlimited')}}</el-button>
              <el-tag
                v-for="tag in dynamicTags"
                :key="tag.userTagId"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >{{tag.tagName}}</el-tag>
              <el-button
                class="button-new-tag"
                size="small"
                @click="selectUserTags()"
              >{{$t('platform.add')}}</el-button>
            </el-form-item>
          </el-row>
        </el-form>
        <!-- <el-button>按钮</el-button> -->
      </template>
      <template slot-scope="scope" slot="status">
        <el-tag v-if="scope.row.status === 0" size="small" type="danger">{{$t('publics.disable')}}</el-tag>
        <el-tag v-else size="small">{{$t('publics.normal')}}</el-tag>
      </template>
      <template slot-scope="scope" slot="levelType">
        <el-tag
          v-if="scope.row.levelType === 0"
          size="small"
          type="info"
        >{{$t('user.ordinaryMember')}}</el-tag>
        <el-tag v-else size="small" type="primary">{{$t('user.paidMembership')}}</el-tag>
      </template>
      <!-- 菜单列 -->
      <template slot-scope="scope" slot="menu">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="small"
          v-if="isAuth('plateform:user:update')"
          @click.stop="addOrUpdateHandle(scope.row.userId)"
        >{{$t('coupon.edit')}}</el-button>
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="small"
          v-if="isAuth('platform:user:updateBalance')"
          @click.stop="updateBalance(scope.row.userId, 0)"
        >{{$t('user.modifyBalance')}}</el-button>
      </template>
    </avue-crud>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="refreshChange"></add-or-update>
    <update-growth v-if="updateGrowthVisible" ref="updateGrowth" @refreshDataList="refreshChange"></update-growth>
    <update-score v-if="updateScoreVisible" ref="updateScore" @refreshDataList="refreshChange"></update-score>
    <update-tags v-if="updateTagsVisible" ref="updateTags" @refreshDataList="refreshChange"></update-tags>
    <update-balance v-if="updateBalanceVisible" ref="updateBalance" @refreshDataList="refreshChange"></update-balance>
    <update-coupon v-if="updateCouponVisible" ref="updateCoupon" :getWay="1" @refreshDataList="refreshChange"></update-coupon>
    <import-user v-if="importUserVisible" ref="importUser" @refreshDataList="refreshChange"></import-user>

    <tags-select
      v-if="tagsSelectVisible"
      :limit="5"
      ref="tagsSelect"
      @refreshTagsArr="refreshTagsSelect"
    ></tags-select>
  </div>
</template>

<script>
import { tableOption } from '@/crud/user/user'
import AddOrUpdate from './user-add-or-update'
import UpdateGrowth from './update-user-growth'
import UpdateScore from './update-user-score'
import UpdateTags from './update-user-tags'
import UpdateBalance from './update-user-balance'
import UpdateCoupon from './update-user-copon'
import ImportUser from './excel-user-import'
import TagsSelect from '@/components/tags-select'

export default {
  data () {
    return {
      dataList: [],
      dataListLoading: false,
      exportDisabled: false,
      importDisabled: false,
      tagsSelectVisible: false,
      updateBalanceVisible: false,
      updateCouponVisible: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      updateGrowthVisible: false,
      updateScoreVisible: false,
      updateTagsVisible: false,
      importUserVisible: false,
      resourcesUrl: window.SITE_CONFIG.resourcesUrl,
      tableOption: tableOption,
      dynamicTags: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10 // 每页显示多少条
      },
      searchForm: {
        userTag: []
      }
    }
  },
  components: {
    AddOrUpdate,
    UpdateGrowth,
    UpdateScore,
    UpdateTags,
    TagsSelect,
    UpdateCoupon,
    ImportUser,
    UpdateBalance
  },
  methods: {
    // 获取数据列表  /admin/user/page
    getDataList (page) {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/admin/user/userPage'),
        method: 'get',
        params: this.$http.adornParams(
          Object.assign(
            {
              current: page == null ? this.page.currentPage : page.currentPage,
              size: page == null ? this.page.pageSize : page.pageSize
            },
            this.searchForm
          )
        )
      }).then(({ data }) => {
        this.dataList = data.records
        this.page.total = data.total
        this.dataListLoading = false
      })
    },
    // 新增 / 修改
    addOrUpdateHandle (id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 条件查询 JSON.stringify(arr)
    searchChange (params) {
      this.searchForm = params
      var arr = ''
      this.dynamicTags.forEach(item => {
        if (item.userTagId === this.dynamicTags[this.dynamicTags.length - 1].userTagId) {
          arr = arr + item.userTagId
          return
        }
        arr = arr + item.userTagId + ','
      })
      this.searchForm.tagIds = arr
      this.getDataList(this.page)
    },
    // 刷新回调用
    refreshChange () {
      this.page = this.$refs.crud.$refs.tablePage.defaultPage
      this.getDataList(this.page)
    },
    // 多选变化
    selectionChange (val) {
      this.dataListSelections = val
    },
    // 修改成长值
    updateGrowth (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      // console.log(ids)
      this.updateGrowthVisible = true
      this.$nextTick(() => {
        this.$refs.updateGrowth.init(ids)
      })
    },
    // 修改成长值
    updateScore (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      // console.log(ids)
      this.updateScoreVisible = true
      this.$nextTick(() => {
        this.$refs.updateScore.init(ids)
      })
    },
    updateTags (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      // console.log(ids)
      this.updateTagsVisible = true
      this.$nextTick(() => {
        this.$refs.updateTags.init(ids)
      })
    },
    // type 1 批次充值 0修改余额
    updateBalance (id, type) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      // console.log(ids)
      this.updateBalanceVisible = true
      this.$nextTick(() => {
        this.$refs.updateBalance.init(ids, type)
      })
    },
    updateCoupon (id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.userId
      })
      // console.log(ids)
      this.updateCouponVisible = true
      this.$nextTick(() => {
        this.$refs.updateCoupon.init(ids)
      })
    },
    // 移除标签单个选项 updateCoupon
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    // 选择客户标签
    selectUserTags () {
      this.tagsSelectVisible = true
      this.$nextTick(() => {
        this.$refs.tagsSelect.init()
      })
    },
    // 清除所有标签
    clearAllTags () {
      this.dynamicTags = []
    },
    // 选择到的标签tagId
    refreshTagsSelect (data) {
      this.clearAllTags()
      this.dynamicTags = data
      this.searchForm.userTag = data
    },
    searchReset () {
      this.clearAllTags()
    },
    //  选择指定列进行排序
    changeTableSort (column) {
      // 获取字段名称和排序类型
      var fieldName = column.prop
      var sortingType = column.order
      this.searchForm.fieldName = fieldName
      this.searchForm.sortingType = sortingType
      this.$set(this.page, this.page)
      this.getDataList(this.page)
    },
    /**
     * 导入用户
     */
    importUser () {
      this.importUserVisible = true
      this.$nextTick(() => {
        this.$refs.importUser.init()
      })
    },
    /**
     * 导出单品
     */
    exportUser () {
      this.exportDisabled = true
      this.$http({
        url: this.$http.adornUrl('/admin/user/exportUser'),
        method: 'get',
        params: this.$http.adornParams(this.searchForm),
        responseType: 'blob' // 解决文件下载乱码问题
      }).then(({ data }) => {
        this.exportDisabled = false
        var blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
        const fileName = this.$i18n.t('user.userInformationForm')
        const elink = document.createElement('a')
        if ('download' in elink) { // 非IE下载
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    }
  }
}
</script>
